"""
任务相关路由
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from datetime import datetime
from app.models import User, Project, ProjectTask
from app import db

# 创建蓝图
task_bp = Blueprint('task', __name__, url_prefix='/task')

@task_bp.route('/')
@login_required
def list_tasks():
    """任务列表"""
    # 获取所有任务
    tasks = ProjectTask.query.all()
    return render_template('task_list.html', tasks=tasks)

@task_bp.route('/create/general', methods=['GET', 'POST'])
@login_required
def task_form_general():
    """创建通用任务"""
    if request.method == 'POST':
        # 处理表单提交
        project_id = request.form.get('project_id')
        name = request.form.get('name')
        parent_id = request.form.get('parent_id', '0')
        assignee_id = request.form.get('assignee_id')
        priority = request.form.get('priority', '中')
        status = request.form.get('status', '未开始')
        start_date = request.form.get('start_date')
        end_date = request.form.get('end_date')
        description = request.form.get('description')
        
        # 验证必填字段
        if not project_id or not name:
            flash('请填写必填字段', 'error')
            # 获取项目列表和用户列表
            projects = Project.query.all()
            users = User.query.all()
            return render_template('task_form_general.html', 
                                 projects=projects, 
                                 users=users)
        
        # 创建新任务
        new_task = ProjectTask(
            project_id=int(project_id),
            name=name,
            parent_id=int(parent_id) if parent_id != '0' else None,
            assignee_id=int(assignee_id) if assignee_id else None,
            priority=priority,
            status=status,
            start_date=datetime.strptime(start_date, '%Y-%m-%d').date() if start_date else None,
            end_date=datetime.strptime(end_date, '%Y-%m-%d').date() if end_date else None,
            description=description,
            creator_id=current_user.id
        )
        
        db.session.add(new_task)
        db.session.commit()
        
        flash('任务创建成功', 'success')
        return redirect(url_for('home'))
    
    # 获取项目列表和用户列表
    projects = Project.query.all()
    users = User.query.all()
    
    return render_template('task_form_general.html', 
                         projects=projects, 
                         users=users)

@task_bp.route('/<int:task_id>')
@login_required
def view_task(task_id):
    """查看任务详情"""
    task = ProjectTask.query.get_or_404(task_id)
    return render_template('task_detail.html', task=task)

@task_bp.route('/<int:task_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_task(task_id):
    """编辑任务"""
    task = ProjectTask.query.get_or_404(task_id)
    
    if request.method == 'POST':
        task.name = request.form.get('name', task.name)
        task.description = request.form.get('description', task.description)
        task.start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else task.start_date
        task.end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else task.end_date
        task.priority = request.form.get('priority', task.priority)
        task.status = request.form.get('status', task.status)
        
        db.session.commit()
        flash('任务更新成功')
        return redirect(url_for('task.view_task', task_id=task_id))
    
    return render_template('task_edit.html', task=task)

@task_bp.route('/<int:task_id>/delete', methods=['POST'])
@login_required
def delete_task(task_id):
    """删除任务"""
    task = ProjectTask.query.get_or_404(task_id)
    db.session.delete(task)
    db.session.commit()
    flash('任务删除成功')
    return redirect(url_for('task.list_tasks'))

@task_bp.route('/<int:task_id>/details')
@login_required
def get_task_details(task_id):
    """获取任务详情"""
    task = ProjectTask.query.get_or_404(task_id)
    return render_template('task_detail.html', task=task)

@task_bp.route('/my')
@login_required
def my_tasks():
    """我的任务"""
    # 获取当前用户创建的任务
    tasks = ProjectTask.query.filter_by(creator_id=current_user.id).all()
    return render_template('my_tasks.html', tasks=tasks)

@task_bp.route('/form', methods=['GET', 'POST'])
@login_required
def task_form():
    """任务表单"""
    if request.method == 'POST':
        # 处理表单提交
        project_id = request.form.get('project_id')
        name = request.form.get('name')
        parent_id = request.form.get('parent_id', '0')
        assignee_id = request.form.get('assignee_id')
        priority = request.form.get('priority', '中')
        status = request.form.get('status', '未开始')
        start_date = request.form.get('start_date')
        end_date = request.form.get('end_date')
        description = request.form.get('description')
        
        # 验证必填字段
        if not project_id or not name:
            flash('请填写必填字段', 'error')
            # 获取项目列表和用户列表
            projects = Project.query.all()
            users = User.query.all()
            return render_template('task_form.html', 
                                 projects=projects, 
                                 users=users)
        
        # 创建新任务
        new_task = ProjectTask(
            project_id=int(project_id),
            name=name,
            parent_id=int(parent_id) if parent_id != '0' else None,
            assignee_id=int(assignee_id) if assignee_id else None,
            priority=priority,
            status=status,
            start_date=datetime.strptime(start_date, '%Y-%m-%d').date() if start_date else None,
            end_date=datetime.strptime(end_date, '%Y-%m-%d').date() if end_date else None,
            description=description,
            creator_id=current_user.id
        )
        
        db.session.add(new_task)
        db.session.commit()
        
        flash('任务创建成功', 'success')
        return redirect(url_for('home'))
    
    # 获取项目列表和用户列表
    projects = Project.query.all()
    users = User.query.all()
    
    # 如果有id参数，表示编辑任务
    task_id = request.args.get('id')
    if task_id:
        task = ProjectTask.query.get_or_404(task_id)
        return render_template('task_form.html', task=task, projects=projects, users=users)
    
    return render_template('task_form.html', projects=projects, users=users)

@task_bp.route('/create/<int:project_id>', methods=['GET', 'POST'])
@login_required
def task_create(project_id):
    """创建项目任务"""
    project = Project.query.get_or_404(project_id)
    
    if request.method == 'POST':
        name = request.form.get('name')
        description = request.form.get('description')
        start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None
        end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None
        priority = request.form.get('priority')
        assignee_id = int(request.form.get('assignee_id')) if request.form.get('assignee_id') else None
        
        # 创建新任务
        new_task = ProjectTask(
            project_id=project_id,
            name=name,
            description=description,
            start_date=start_date,
            end_date=end_date,
            priority=priority,
            assignee_id=assignee_id,
            creator_id=current_user.id
        )
        
        db.session.add(new_task)
        db.session.commit()
        
        flash('任务创建成功', 'success')
        return redirect(url_for('project.view_project', project_id=project_id))
    
    # 获取可分配的用户列表
    users = User.query.all()
    return render_template('task_form.html', project=project, users=users)